package com.mk.api.sys;

import com.mk.base.model.response.Rsp;
import com.mk.model.request.OrgRequest;
import com.mk.service.IOrgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * @Author: yq
 * @Description:
 * @Date: Created in 11:56 AM 3/14/18
 */
@RestController
@RequestMapping("/org")
public class OrgApi {

    @Autowired
    private IOrgService orgService;

    @RequestMapping(method = RequestMethod.POST)
    public Rsp saveOrg(@RequestBody OrgRequest request){
        try{
            return Rsp.SUCCESS(orgService.save(request));
        }catch (Exception e){
            return Rsp.ERROR(e.getMessage());
        }
    }

    @RequestMapping(method = RequestMethod.PUT)
    public Rsp updateOrg(@RequestBody OrgRequest request){
        try{
            if(orgService.update(request))
                return Rsp.SUCCESS("编辑组织信息成功");
            else
                return Rsp.ERROR("编辑组织信息失败");
        }catch (Exception e){
            return Rsp.ERROR(e.getMessage());
        }
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    public Rsp deleteOrg(@PathVariable("id") Long id){
        try{
            if(orgService.delete(id))
                return Rsp.SUCCESS("删除组织信息成功");
            else
                return Rsp.ERROR("删除组织信息失败");
        }catch (Exception e){
            return Rsp.ERROR(e.getMessage());
        }
    }

    @RequestMapping(value = "/del",method = RequestMethod.DELETE)
    public Rsp deleteOrgs(Long... ids){
        try{
            if(orgService.deleteChilds(Arrays.asList(ids)))
                return Rsp.SUCCESS("删除组织部门及其子部门成功");
            else
                return Rsp.SUCCESS("删除组织部门及其子部门失败");
        }catch (Exception e){
            return Rsp.ERROR(e.getMessage());
        }
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public Rsp findOne(@PathVariable("id") Long id){
        try {
            return Rsp.SUCCESS(orgService.get(id));
        }catch (Exception e){
            return Rsp.ERROR(e.getMessage());
        }
    }

    @RequestMapping(method = RequestMethod.GET)
    public Rsp findAll(OrgRequest request){
        try{
            return Rsp.SUCCESS(orgService.getAll(request));
        }catch (Exception e){
            return Rsp.ERROR(e.getMessage());
        }
    }
}
